import { defineStore } from 'pinia'
import { collectionHelpers } from './modelStore'
import api from '@/api'

export const useIndicatorStore = defineStore('indicators', {
  state: () => ({
    loading: true,
    error: false,
    collection: [],
    current: null,
  }),
  actions: {
    loadFromNodes: async function (nodeIds) {
      this.collection = []
      const result = []
      await Promise.all(
        nodeIds.map(async (nodeId) => {
          const indicators = await api.indicators.getIndicators(nodeId, {
            filters: { scoped: 1 },
          })
          result.push(...indicators)
        })
      )
      this.collection = result
    },
    loadFromNode: async function (nodeId) {
      const indicators = await api.indicators.getIndicators(nodeId, {
        filters: { scoped: 1 },
      })

      const by_ids = {}
      indicators.forEach((item) => {
        if (!by_ids[item.id]) {
          by_ids[item.id] = item
        }
      })
      /** Find the items in this.collection which are also in indicators
       * also update this.collection with the new indicators
       */
      this.collection = this.collection.map((item, index) => {
        if (by_ids[item.id]) {
          return by_ids[item.id]
        } else {
          return item
        }
      })
    },
    loadItem: async function (itemId) {
      this.loading = true
      const indicator = await api.indicators.load(itemId)
      this.collection = this.collection.map((item) => {
        if (item.id === indicator.id && item.node_id === indicator.node_id) {
          return indicator
        } else {
          return item
        }
      })
      this.loading = false
    },
    validateIndicator: async function (indicator) {
      console.log('validateIndicator', indicator.id)
      this.loading = true
      try {
        this.current = await api.indicators.validateIndicator(indicator)
        // Replace the indicator with same id from collection with the current indicator
        this.collection = this.collection.map((item) => {
          if (item.id === indicator.id && item.node_id === indicator.node_id) {
            return this.current
          } else {
            return item
          }
        })

        this.error = null
      } catch (error) {
        this.error = error
      } finally {
        this.loading = false
      }
    },
    forceIndicator: async function (indicator) {
      console.log('forceIndicator', indicator.id)
      this.loading = true
      try {
        this.current = await api.indicators.forceIndicator(indicator)
        // Replace the indicator with same id from collection with the current indicator
        this.collection = this.collection.map((item) => {
          if (item.id === indicator.id && item.node_id === indicator.node_id) {
            return this.current
          } else {
            return item
          }
        })

        this.error = null
      } catch (error) {
        this.error = error
      } finally {
        this.loading = false
      }
    },
  },
  getters: {
    getByNodeId:
      (state) =>
      (nodeId, requirement_types = null) => {
        let result = state.collection.filter((item) => {
          if (requirement_types === null) {
            return item.node_id === nodeId
          } else {
            return (
              item.node_id === nodeId &&
              requirement_types.includes(item.requirement_type)
            )
          }
        })
        return result
      },
    getByTypeId:
      (state) =>
      (fileTypeId, nodeId = null) => {
        let result = state.collection.find((item) => {
          if (item.file_type_id === fileTypeId) {
            if (nodeId === null) {
              return true
            } else {
              return item.node_id === nodeId
            }
          }
        })

        return result
      },
    ...collectionHelpers('indicators'),
  },
})
